import * as React from 'react';
import {ComponentDecorator, connect} from 'react-redux';
import {DragDropContext} from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';

import './DesignerPane.css';
import WidgetPane from '../widget/WidgetPane';
import AttributePane from '../attribute/AttributePane';
import CanvasPane from '../canvas/CanvasPane';
import {IDesign} from '../../types/IDesign';
import {IView} from '../../types/IView';
import store, {AppState} from '../../store/index';
import HierarchyPane from '../hierarchy/HierarchyPane';
import {ActionType} from '../../store/ActionType';

export interface DesignerPaneOwnProps {
  design: IDesign;
}

export interface DesignerPaneMergedProps {
  selectedView?: IView;
}

type DesignerPaneProps = DesignerPaneOwnProps & DesignerPaneMergedProps;

function mapStateToProps(state: AppState, ownProps: DesignerPaneOwnProps): DesignerPaneMergedProps {
  const designId = ownProps.design.id;

  const selectedView = state.selectedViewState[designId];
  if (!selectedView) {
    return {};
  }

  return {
    selectedView
  };
}

class DesignerPane extends React.Component<DesignerPaneProps, undefined> {
  componentDidMount() {
    // React 不能直接在render 绑定div 的keydown 事件, 只能这样处理了
    document.addEventListener('keydown', this.keyHandler);
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.keyHandler);
  }

  render() {
    return (
      <div className="Designer">
        <CanvasPane design={this.props.design} selectedView={this.props.selectedView}/>
        <HierarchyPane design={this.props.design} selectedView={this.props.selectedView}/>
        <WidgetPane/>
        {this.renderAttributePane()}
      </div>
    );
  }

  private renderAttributePane() {
    if (this.props.selectedView) {
      return (
        <AttributePane designId={this.props.design.id} selectedView={this.props.selectedView}/>
      );
    }
  }

  private keyHandler = (event: KeyboardEvent) => {
    const {design, selectedView} = this.props;
    if (!selectedView || event.key !== 'Delete') {
      // 没有选择组件, 或者按的不是 删除 键, 则不处理
      return;
    }

    if (selectedView.id === design.root.id) {
      // 如果是设计 的 根组件, 也不处理, 不然根组件都被删除了
      return;
    }

    if (event.srcElement.tagName.toLowerCase() === 'input') {
      return;
    }

    // 删除组件
    store.dispatch({
      type: ActionType.REMOVE_VIEW,
      designId: design.id,
      viewId: selectedView.id
    });
  }
}

type DesignPaneDecorator = ComponentDecorator<DesignerPaneMergedProps, DesignerPaneOwnProps>;
const componentDecorator: DesignPaneDecorator = connect(mapStateToProps);
export default componentDecorator(DragDropContext(HTML5Backend)(DesignerPane));
